package com.tedu.web;


import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public boolean checkLogin(String username, String password){
        boolean flag = false;
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
		/*
		创建Connnection, Statement, ResultSet对象
		调用验证登录的方法
		*/
        System.out.println("name："+username+" password："+password);
        String sql ="select * from user where username = '"+ username +"'";
        conn = JdbcUtil.getConnection();
        System.out.println("conn =  "+conn);
        try {
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()){
                if(rs.getString("password").equals(password)){
                    flag = true;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(rs, st, conn);
        }
        return flag;
    }

    public boolean register(String username, String password){
        Connection conn = null;
        PreparedStatement pst = null;
        Boolean flag = false;
        String sql = "insert into user(username,password) values(?,?)";
        try{
            conn = JdbcUtil.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1, username);
            pst.setString(2, password);
            int b = 0;
            pst.execute();
            System.out.println("b= " + b);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtil.close(pst,conn);
        }

        return flag;

    }

    public ArrayList<User> userList() throws SQLException {
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        String sql = "select * from user";
        ArrayList<User> list = new ArrayList<User>();
        try{
            conn = JdbcUtil.getConnection();
            statement = conn.createStatement();
            resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                list.add(user);
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtil.close(resultSet,statement,conn);
        }
        return null;
    }

}
